// Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.

// 删除vpc
package vpc

import (
	"fleetmanager/client"
	"fleetmanager/workflow/components"
	"fleetmanager/workflow/directer"
	"fleetmanager/workflow/meta"
	"fmt"

	vpcmodel "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model"
)

type DeleteVpcTask struct {
	components.BaseTask
}

// Execute 执行删除vpc任务
func (t *DeleteVpcTask) Execute(ctx *directer.ExecuteContext) (output interface{}, err error) {
	defer func() { t.ExecNext(output, err) }()
	projectId := t.Directer.GetContext().Get(directer.WfKeyProjectId).ToString("")
	accessKey := t.Directer.GetContext().Get(directer.WfKeyAccessKey).ToString("")
	secretAccessKey := t.Directer.GetContext().Get(directer.WfKeySecurityAccessKey).ToString("")
	regionId := t.Directer.GetContext().Get(directer.WfKeyRegion).ToString("")
	var vpcName = ""
	var vpcId = ""

	fleetId := t.Directer.GetContext().Get(directer.WfKeyFleetId).ToString("")
	// 尝试根据FleetID为VPC Name获取VPC，获取的到说明是自己创建的，可以被删除
	if fleetId != "" {
		vpc, err := GetVpc(regionId, projectId, accessKey, secretAccessKey, fleetId)
		if err != nil {
			return nil, err
		}
		if vpc == nil {
			return nil, nil
		}
		vpcId = vpc.Id
		vpcName = vpc.Name
	} else {
		return nil, fmt.Errorf("fleet id is null")
	}

	if vpcId == "" || vpcName != fleetId {
		// 没有创建vpc, 或使用的指定的VPC创建的资源，不删除VPC
		return nil, nil
	}

	// 删除vpc
	if err := deleteVpc(regionId, projectId, accessKey, secretAccessKey, vpcId); err != nil {
		return nil, err
	}

	// 等待vpc删除完成
	if err := waitVpcDeleted(regionId, projectId, accessKey, secretAccessKey, vpcId); err != nil {
		return nil, err
	}

	return nil, nil
}

var GetVpc = func(regionId string, projectId string, accessKey string, secretAccessKey string,
	vpcName string) (*vpcmodel.Vpc, error) {
	vpcClient := client.GetVpcClient(accessKey, secretAccessKey, regionId, projectId)
	vpc, err := client.GetVpc(vpcClient, &vpcName)
	return vpc, err
}

var GetVpcById = func(regionId string, projectId string, accessKey string, secretAccessKey string,
	vpcId string) (*vpcmodel.Vpc, error) {
	vpcClient := client.GetVpcClient(accessKey, secretAccessKey, regionId, projectId)
	vpc, err := client.GetVpcById(vpcClient, &vpcId)
	return vpc, err
}

var deleteVpc = func(regionId string, projectId string, accessKey string, secretAccessKey string, vpcId string) error {
	vpcClient := client.GetVpcClient(accessKey, secretAccessKey, regionId, projectId)
	return client.DeleteVpc(vpcClient, &vpcId)
}

var waitVpcDeleted = func(regionId string, projectId string, accessKey string, secretAccessKey string, vpcId string) error {
	vpcClient := client.GetVpcClient(accessKey, secretAccessKey, regionId, projectId)
	return client.WaitVpcDeleted(vpcClient, &vpcId)
}

// NewDeleteVpcTask 新建vpc删除任务
func NewDeleteVpcTask(meta meta.TaskMeta, directer directer.Directer, step int) components.Task {
	t := &DeleteVpcTask{
		components.NewBaseTask(meta, directer, step),
	}

	return t
}
